/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, {Component} from 'react';
import {
    DeviceEventEmitter,
    ListView,
    RefreshControl,
    ScrollView,
    StyleSheet,
    Text,
    TouchableOpacity,
    View,
} from 'react-native';


import StyleUtils from "../../../res/styles/StyleUtils";
import Navigation from "../../../custom/Navigation";
import ViewUtils from "../../../utils/ViewUtils";
import ModalListUtils from "../../../utils/ModalListUtils";
import IparNetwork, {getSynPaysSellerAuth, SERVER_TYPE} from "../../../httpUtils/IparNetwork";
import CommonUtils from "../../../common/CommonUtils";
import I18n from "../../../res/language/i18n";
import AddBackCardPage from "../bankCard/AddBackCardPage";
import {KeyboardAwareScrollView} from 'react-native-keyboard-aware-scroll-view'
import IparInput from "../../../custom/IparInput";
import UserEmailEdit from "../userInfo/UserEmailEdit";
import BaseModal from "../../../utils/BaseModal";


let bankCard = [];
let shopData = [];
let verCodeBtn = false;
export default class WithdrawPage extends Component {

    constructor(props) {
        super(props);
        let ds = new ListView.DataSource({rowHasChanged: (r1, r2,) => r1 !== r2});
        bankCard = [];
        this.state = {
            bankCardIndex: '',
            showDialog: false,
            modalVisible: false,
            dataSource: ds.cloneWithRows(bankCard),
            userId: '',
            showLoading: false,
            amountEdit: '',
            cardId: '',
            selectData: {},
            withdrawType: "",
            mobile: '',
            verificationCode: I18n.t('default.getCode')
        };
        this.iparNetwork = new IparNetwork()
    }

    componentWillUnmount() {
        this.iparNetwork = null;
    }

    componentDidMount() {


        /*获取本地数据*/
        CommonUtils.getAcyncInfo('userInfo')
            .then((result) => {
                let parse = JSON.parse(result);
                this.country = parse.country;

                this.userName = parse.user_name == null ? parse.nick_name : parse.user_name;
                this.setState({
                    userId: parse.main_user_id,
                    mobile: parse.mobile,
                });
                this.onLoadData()
                // this.getDebitCardInfo();

            });


    }


    /**
     * 获取数据
     */
    onLoadData() {
        if (this.props.type === 0) {
            this.getShopsInfo();
        } else {
            this.getCreditCardInfo();
        }
    }

    /*获取验证码时间*/
    countTime() {
        if (verCodeBtn === false) {
            verCodeBtn = true;
            this._index = 60;
            this._timer = setInterval(() => {
                this.setState({verificationCode: this._index-- + ' s'});
                if (this.state.verificationCode <= 0 + ' s') {
                    this._timer && clearInterval(this._timer);
                    verCodeBtn = false;
                    this.setState({verificationCode: I18n.t('toast.againGetCode')});
                }
            }, 1000);
        }

    }


    /**
     * 获取实体店的数据
     */
    getShopsInfo() {
        this.setState({showLoading: true});

        this.iparNetwork.getRequest(SERVER_TYPE.adminIpar + 'getWareHouse?', 'country=' + this.country)
            .then((result) => {
                if (result.code === 200) {
                    shopData = [];
                    shopData = result.data;
                    this.setState({
                        dataSource: this.state.dataSource.cloneWithRows(shopData),
                        showLoading: false, loading: false
                    })
                } else {
                    this.setState({showLoading: false, loading: false});
                    DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                }
            })
            .catch((error) => {
                this.setState({showLoading: false, loading: false});
                console.log('WithdrawPage-----getShopsInfo-error-', error);
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
            })

    }

    /*获取借记卡*/
    getDebitCardInfo() {
        this.iparNetwork.getRequest(SERVER_TYPE.synPays + 'DebitCard?', 'Auth=' + getSynPaysSellerAuth(this.country, 1) + '&UserID=' + this.state.userId)
            .then((result) => {
                this.setState({
                    showLoading: false, loading: false
                });
                if (result.ApiResponseCode === 200) {
                    for (i = 0; i < result.data.length; i++) {
                        bankCard.push(result.data[i]);
                    }

                    this.setState({dataSource: this.state.dataSource.cloneWithRows(bankCard)})
                }
            })
            .catch((error) => {
                this.setState({showLoading: false, loading: false});
                console.log(error);
            });


    }

    /*获取使用卡*/
    getCreditCardInfo() {
        bankCard = [];
        this.setState({showLoading: true});
        this.iparNetwork.getRequest(SERVER_TYPE.adminIpar + 'getCardInfo?', 'UserID=' + this.state.userId+'&Type=CreditCard')
            .then((result) => {
                this.setState({
                    showLoading: false, loading: false,
                });
                console.log(result);
                if (result.code === 200) {
                    for (let i = 0; i < result.data.length; i++) {
                        bankCard.push(result.data[i]);
                    }
                    bankCard.push({CardNumber: I18n.t('default.addCard')});
                    this.setState({dataSource: this.state.dataSource.cloneWithRows(bankCard)})
                } else {
                    bankCard.push({CardNumber: I18n.t('default.addCard')});
                    this.setState({dataSource: this.state.dataSource.cloneWithRows(bankCard)})
                }

            })
            .catch((error) => {
                this.setState({showLoading: false, loading: false});
                console.log(error);
            })
    }

    /*提现借口*/
    getWithdrawal() {
        let data =
            {
                UserID: this.state.userId,
                Amount: (parseFloat(this.state.amountEdit)).toFixed(2),
                WithdrawalTo: this.state.withdrawType,
                ID: this.state.cardId,
                OperatorID: this.state.userId,
                AccountName: this.userName,
                StoreName: this.state.bankCardIndex,
                OperatorName: this.userName,
                Note: 'User application',
            };


        let formData = new FormData();
        formData.append("withdraw_type", "In");
        formData.append("Currency", this.props.getPv);
        formData.append("Country", this.country);
        formData.append("TaxRate", this.taxData.TaxRates);
        formData.append("TaxAmount", this.taxData.TaxFee);
        formData.append("ServiceFee", this.taxData.Service_fee);
        formData.append("Total", this.taxData.Total);
        formData.append("Amount", this.taxData.Amount);
        formData.append("WithdrawalTo", this.state.withdrawType);
        formData.append("UserID", this.state.userId);
        formData.append("ID", this.state.cardId);
        formData.append("Note", 'User application');
        formData.append("AccountName", this.userName);
        formData.append("StoreName", this.state.bankCardIndex);
        formData.append("OperatorName", this.userName);
        formData.append("OperatorID", this.state.userId);


        this.iparNetwork.getPostFrom(SERVER_TYPE.adminIpar + 'Withdrawal', formData)
            .then((result) => {
                console.log(result);
                CommonUtils.dismissLoading();
                if (result.code === 200) {
                    DeviceEventEmitter.emit('toast', I18n.t('default.success'));
                    this.props.navigator.pop();
                    this.props.callback('ok')
                }
            })
            .catch((error) => {
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                CommonUtils.dismissLoading();
                console.log(error);
            })
    }

    render() {


        let isRecharge = this.props.type === 2;

        let isShop = this.props.type === 0;
        let _selectMenuText = isShop ? I18n.t('default.selectShop') : I18n.t('default.selectBankCard');

        const {modalVisible} = this.state;

        return (
            <View style={StyleUtils.flex}>
                <Navigation
                    onClickLeftBtn={() => {
                        this.props.navigator.pop()
                    }}
                    leftButtonIcon={require('../../../res/images/ic_back.png')}
                    titleImage={require('../../../res/images/ic_ipar_logo.png')}
                />
                <ModalListUtils
                    onPress={(index) => {

                        if (this.props.type === 0) {


                            this.setState({
                                showDialog: false,
                                bankCardIndex: shopData[index].name,
                                cardId: shopData[index].warehouse_id,
                                withdrawType: 3,
                            });
                        } else {
                            if (bankCard[index].CardNumber === I18n.t('default.addCard')) {
                                this.setState({
                                    showDialog: false,
                                }, this.props.navigator.push({
                                    component: AddBackCardPage,
                                    params: {
                                        callback: () => {
                                            this.onLoadData();
                                        }
                                    }
                                }));
                                return
                            }
                            this.setState({
                                bankCardIndex: bankCard[index].CardNumber,
                                showDialog: false,
                                cardId: bankCard[index].CardID,
                                withdrawType: bankCard[index].ExpirationDate === undefined ? '1' : 2,
                            });
                        }
                    }}
                    close={() => {
                        this.setState({
                            showDialog: false
                        })
                    }}
                    visible={this.state.showDialog}
                    dataSource={this.state.dataSource}
                    dataParam={isShop ? 'name' : 'CardNumber'}
                />
                <KeyboardAwareScrollView

                    refreshControl={
                        <RefreshControl
                            refreshing={this.state.showLoading}
                            onRefresh={() => this.onLoadData()}
                        />
                    }


                >
                    <View style={{padding: 16, height: '100%'}}
                    >
                        {ViewUtils.getTitleView(isRecharge ? I18n.t('default.recharge') : I18n.t('default.withdrawal'), isRecharge ? '' : I18n.t('default.availableBalance'))}

                        <Text
                            style={[StyleUtils.smallTvColor, styles.amountTv, StyleUtils.smallFont]}>{this.props.balance + this.props.getPv}</Text>

                        <IparInput
                            keyboardType={'numeric'}
                            onChangeText={(amount) => {
                                this.setState({amountEdit: amount})
                            }}
                            placeholder={isRecharge ? 'Enter recharge amount' : I18n.t('default.enterWithdrawAmount')}/>


                        {ViewUtils.getButtunMenu(this.state.bankCardIndex ? this.state.bankCardIndex : _selectMenuText, () => {
                            this.setState({showDialog: true});
                        }, {marginTop: 16})}

                        <IparInput
                            isPassword={!isRecharge}
                            onChangeText={(text) => this.userPass = text}
                            placeholder={isRecharge ? I18n.t('default.cvv') : I18n.t('default.enterYourPassword')}/>

                        {ViewUtils.getButton(I18n.t('default.submit'), () => {
                            this.submitBtn()
                        }, {marginTop: 30})}


                        <TouchableOpacity
                            onPress={() => {
                                this.props.navigator.push({
                                    component: UserEmailEdit,
                                    params: {
                                        mobile: this.state.mobile,
                                        type: 1,
                                    }
                                })
                            }}
                            style={{padding: 8, marginTop: 16}}>

                            <Text style={{width: '100%', textAlign: 'center'}}>{I18n.t('default.forgotPass')}</Text>

                        </TouchableOpacity>

                    </View>

                </KeyboardAwareScrollView>


                <BaseModal
                    visible={modalVisible && this.taxData}
                    requestClose={() => {
                        this.setState({modalVisible: false})
                    }}>

                    <View style={{alignItems: 'center', height: '100%', justifyContent: 'center'}}>


                        {this.taxData &&
                        <View style={{width: 300, padding: 16, backgroundColor: 'white', borderRadius: 8}}>

                            <Text style={{marginTop: 4, color: 'gray'}}>金额 : {this.taxData.Amount}</Text>
                            <Text style={{marginTop: 4, color: 'gray'}}>服务费 : {this.taxData.Service_fee}</Text>
                            <Text style={{marginTop: 4, color: 'gray'}}>税费 : {this.taxData.TaxFee}</Text>
                            <Text style={{marginTop: 4, color: 'gray'}}>税率 : {this.taxData.TaxRates}</Text>
                            <Text style={{marginTop: 4, color: 'gray'}}>总额 : {this.taxData.Total}</Text>
                            <Text style={{marginTop: 8, marginBottom: 16,}}>你要确认吗</Text>

                            <View style={[StyleUtils.rowDirection]}>
                                <TouchableOpacity
                                    onPress={() => {
                                        this.setState({modalVisible: false});
                                        this.verificationPassword();
                                    }}
                                    style={[
                                        {flex: 1, backgroundColor: 'black', height: 28, marginRight: 4},
                                        StyleUtils.center,
                                    ]}>
                                    <Text style={{color: 'white'}}>yes</Text>
                                </TouchableOpacity>

                                <TouchableOpacity
                                    onPress={() => {
                                        this.setState({modalVisible: false})
                                    }}
                                    style={[
                                        {flex: 1, height: 28, borderColor: 'gray', borderWidth: 1, marginLeft: 4},
                                        StyleUtils.center,
                                    ]}>
                                    <Text style={{color: 'black'}}>no</Text>
                                </TouchableOpacity>
                            </View>

                        </View>}

                    </View>

                </BaseModal>

            </View>


        );
    }


    /**
     * 充值
     */
    recharge() {
        let data =
            {
                Auth: getSynPaysSellerAuth(this.country, 1),
                UserID: this.state.userId,
                SequenceNumber: new Date() + '',
                Amount: (parseFloat(this.state.amountEdit)).toFixed(2),
                Currency: this.props.getPv,
                PayFrom: '2',
                Code: this.state.cardId,
                CVV2: this.userPass,
            };

        this.iparNetwork.getPostJson(SERVER_TYPE.adminIpar + 'Recharge', data)
            .then((result) => {
                CommonUtils.dismissLoading();

                this.setState({
                    showLoading: false,
                });
                console.log(JSON.stringify(result));
                if (result.ApiResponseCode === 200) {
                    DeviceEventEmitter.emit('toast', I18n.t('default.success'));
                    this.props.navigator.pop();
                    this.props.callback('ok')
                }
            })
            .catch((error) => {
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                this.setState({showLoading: false,});
                CommonUtils.dismissLoading();

                console.log(error);
            })
    }

    /*onPressBtn btn 点击*/
    submitBtn() {
        if (this.state.amountEdit === '') {
            DeviceEventEmitter.emit('toast', I18n.t('toast.withdrawAmount'))
        } else if (this.state.bankCardIndex === '') {
            DeviceEventEmitter.emit('toast', I18n.t('default.selectBankCard'))
        } else if (this.props.balance < this.state.amountEdit) {
            DeviceEventEmitter.emit('toast', I18n.t('default.deficiency'))
        } else if (!this.userPass) {
            DeviceEventEmitter.emit('toast', I18n.t('default.enterYourPassword'))
        } else {
            CommonUtils.showLoading();


            if (this.props.type === 2) {
                this.recharge();
            } else {
                this.getTaxInfo();
            }
        }
    }


    /**
     * 获取服务费
     */
    getTaxInfo() {
        let data = {
            Country: this.country,
            WithdrawalTo: this.state.withdrawType,
            Amount: (parseFloat(this.state.amountEdit)).toFixed(2),
            action: 1,
            type: 1,
        };

        this.iparNetwork.getPostJson(SERVER_TYPE.adminIpar + "getWithTaxRate", data)
            .then((res) => {
                if (res.code === 200) {
                    this.taxData = res.data;
                    this.setState({
                        modalVisible: true,
                    });
                } else {
                    DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                }

            })
            .catch((err) => {
                CommonUtils.dismissLoading();
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                console.log(err);
            })
    }


    /**
     * 验证用户登录密码
     */
    verificationPassword() {
        CommonUtils.showLoading();
        let formData = new FormData();
        formData.append('name', this.state.mobile);
        formData.append('password', this.userPass);
        this.iparNetwork.getPostFrom(SERVER_TYPE.centerIpar + 'login', formData)
            .then((result) => {
                if (result.code === 200) {
                    this.getWithdrawal();
                } else {
                    CommonUtils.dismissLoading();
                    if (result.message === '密码错误') {
                        DeviceEventEmitter.emit('toast', I18n.t('toast.passwordNo'))
                    } else {
                        DeviceEventEmitter.emit('toast', I18n.t('default.fail'))
                    }
                }
            })
            .catch((error) => {
                CommonUtils.dismissLoading();
                console.log('withdrawPage erroe--' + error);
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'))
            })

    }


}
const styles = StyleSheet.create({
    amountTv: {
        height: 50,
        fontSize: 30,
        textAlign: 'center'
    },
    numberTv: {
        fontSize: 17,
        color: 'black',
        marginTop: 14,
    }
});
